--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local log = require "Log"
-- local config = require "configquery"
local NodeMessage = require "NodeMessage"
local sharedata = require "sharedata"
require "common"

-- local AssertEx = AssertEx


local Command = class("Command")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function Command:ctor(message)
	self.msg = message
	self.tableList = {} --房间列表
	-- self.is_open = true
	self.closeAll = false --全部游戏关闭
	self.tbClosedGame = {} --已关闭的游戏
	self.nodeMessage = NodeMessage.new()
	self.roomConfig = {}
	self.dbmgr = nil

	self:register()

	--数据库
	local tables = {
		-- { name="fwqp_stock", pk='id',key='gameid', indexkey='' }, --库存表
		-- { name="common_room", pk='id',key='sub_id' },
		-- { name="private_tables", pk='id',key='tableid' },
	}
	self.dbmgr = skynet.uniqueservice("dbmgr_service")
	skynet.call(self.dbmgr, "lua", "start", tables)
	self:loadConfig()

	--mysql日记操作服务
	local logData = {host = skynet.getenv("mysql_host"),
				  port = skynet.getenv("mysql_port"),				  
				  user = skynet.getenv("mysql_user"),
				  password = skynet.getenv("mysql_pwd"),
				  database = "qicaipoker_log",
				  serviceName = "mysql_log",
				 }
	self.mysqlLog = skynet.newservice("mysql_service")
	skynet.call(self.mysqlLog, "lua", "start", logData)
	
	skynet.fork(function()
		self:loop()
	end)		
end

--注册本服务里的消息
function Command:register()

	self.msg:registerSelf('calldb',handler(self,self.calldb))
	self.msg:registerSelf('senddb',handler(self,self.senddb))
	self.msg:registerSelf('Request',handler(self,self.request))
	self.msg:registerSelf('Command',handler(self,self.command))
	self.msg:registerSelf('safe_close',handler(self,self.safeClose))
	self.msg:registerSelf('clear_table',handler(self,self.clearTable))

end

function Command:test()
	print("###777 test###"..type(self.msg))
end


--加载游戏配置
function Command:loadConfig()

	local sqlStr = "select * from common_room"	
	local data = self.nodeMessage:callService("mysql_service",'execute',sqlStr)
	local configData = {}	
	local shardName
	for k,v in pairs(data) do 

		if g_gameType[v.gameid] and next(g_gameType[v.gameid]) then		
			shardName = g_gameType[v.gameid].cfgRoom
			configData[v.sub_id] = v
			if configData and next(configData) then 			
				if not self.roomConfig[shardName] then 					
			 		sharedata.new(shardName, configData)		 		
			 		self.roomConfig[shardName] = configData
			    else
			        sharedata.update(shardName, configData)
			        self.roomConfig[shardName] = configData
			    end		
			end	    
		end
		-- print("_________loadConfig___",shardName,self.roomConfig[shardName])
	end
end

function Command:loop()
	while true do 
		skynet.sleep(600)
		self:loadConfig()
	end
end

---------------------------------------------------------
-- CMD
---------------------------------------------------------

function Command:calldb(cmd,...)
	return skynet.call(self.dbmgr,'lua',cmd,...)
end

function Command:senddb(cmd,...)
	skynet.send(self.dbmgr,'lua',cmd,...)
end

function Command:request(tableid, cmd, ...)
	-- print("______self.tbClosedGame_______",self.tbClosedGame,self.closeAll)
	print("_______Command:request(tableid, cmd, ...)", tableid, cmd, ...)
	local h = self.tableList[tableid]
	local gameid = getGameIdbyTable(tableid)	
	if not h then 
		--桌子不存在
		if self.closeAll or self.tbClosedGame[gameid] then 
			--游戏在维护中
	 		cmd = string.gsub(cmd,'_req','_res',1)
	 		local res = {}
			res[cmd]=GetErrorTable(7)
			return res
		end			
		if cmd == 'enter_table_req' then					
			--桌子创建
			local roomid = getRoomType(tableid)
			local serviceName = getGameService(roomid)	
			local tb = {...}
			local svrid = tb[3] --服务类型1房卡
			if serviceName then 	
				h = skynet.newservice(serviceName,tableid,roomid,svrid)
				self.tableList[tableid] = h
			end	
		else		
			--发生错误
			log.error('cmd Request tableid('..tostring(tableid)..') no exist cmd('..tostring(cmd)..')')
	 		cmd = string.gsub(cmd,'_req','_res',1)
	 		local res = {}
			res[cmd]={err_no=1,err_msg='错误请求'}	
			return res		
		end
	end	
	
	return skynet.call(h, 'lua', cmd, ...)
end

function Command:command( tableid, cmd, ...)
	local h = self.tableList[tableid]
	print("-------------------->Command:command", h ,tableid, cmd, ...)
	if not h then 
		log.error('cmd tableid('..tostring(table_id)..') no exist cmd('..tostring(cmd)..')')
 		cmd = string.gsub(cmd,'_req','_res',1)
 		local res = {}
		res[cmd]={err_no=1,err_msg='错误请求'}
		return res
	end
	return skynet.send(h, 'lua', cmd, ...)
end


--安全关服
function Command:safeClose(close,gameid)
	print("____关游戏___",close,gameid)
	if gameid == 0 then 
		--关所有游戏
		self.closeAll = close
		if table.size(self.tableList) == 0 then 
			--所有桌子清理完成通知gate, 如果有多个game进程需要再处理,现在只有一个game进程
			if self.closeAll then
				self.nodeMessage:sendAllGateManager('safe_close',self.closeAll)
				return
			end
		end		
		for k,v in pairs(self.tableList) do 
			self.nodeMessage:sendService(v,'safe_close',close)
		end				
		return 
	else		
		self.tbClosedGame[gameid] = close
		if close then 
			for k,v in pairs(self.tableList) do 
				if gameid == getGameIdbyTable(k) then 
					self.nodeMessage:sendService(v,'safe_close',close)
					return
				end
			end				
		end
	end
	
end

--桌子服务关闭后返回
function Command:clearTable(tableid)
	--等服务安全关闭后再置空列表
	self.tableList[tableid] = nil	
	if table.size(self.tableList) == 0 then 
		--所有桌子清理完成通知gate, 如果有多个game进程需要再处理,现在只有一个game进程
		if self.closeAll then
			self.nodeMessage:sendAllGateManager('safe_close',self.closeAll)
		end
	end

end


return Command